package ua.org.enginer.managers
{
	import flash.display.DisplayObject;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.describeType;
	
	import mx.containers.ViewStack;
	import mx.core.Application;
	import mx.core.Container;
	import mx.managers.PopUpManager;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import ua.org.enginer.controls.HelpTip;
	
	public class HelpManager extends EventDispatcher
	{
		private var helpData:XML
		private var delegate:Container;
		private var map:Dictionary
		//private var tipOverlay:Container
		private var tips:Array = []
		
		private static var _instance:HelpManager;
		public static function get instance():HelpManager {
			if (!_instance) {
				_instance = new HelpManager(Application.application as Container);
			}
			return _instance;
		}
		
		public function HelpManager(delegate:Container)
		{
			this.delegate = delegate;
			buildMap()
			load()
			
		}
		
		public function refresh():void {
			for each(var tip:HelpTip in tips) {
				//PopUpManager.removePopUp(tip)
				tip.visible = tip.includeInLayout = false
				//tip = null
			}
			tips = []
			buildMap()
			applyHelpData()
		}
		
		public function buildMap():void {
			map = new Dictionary()
			fillMap(delegate.getChildren())
		}
		
		public function addHelpTips(data:XML):void {
			var tip:HelpTip = new HelpTip()
			tip.x = data.@x
			tip.y = data.@y
			tip.htmlText = data
			
			PopUpManager.addPopUp(tip, Application.application as DisplayObject)
			tips.push(tip)
		}
		
		private function fillMap(childs:Array):void {
			for each(var o:DisplayObject in childs){
				if (o is ViewStack){
					//if (o.selectedIndex <= 0 )
						//addToMap(o.getChildAt(0))
					//else
					o = ViewStack(o).selectedChild
					addToMap(o)
				}else if (o.visible) 
					addToMap(o)
					
				if (o is Container)
					fillMap(Container(o).getChildren())
			}
		}
		
		private function addToMap(o:DisplayObject):void {
			var metadata:XML = describeType(o)
			
			map[metadata.@name.toString()] = 1
			
			for each(var clazz:XML in metadata.extendsClass) {
				map[clazz.@type.toString()] = 1
			}
			
		}
		
		public function load():void {
			var service:HTTPService = new HTTPService()
			service.url = "help/help.xml"
			service.resultFormat = HTTPService.RESULT_FORMAT_E4X
			
			service.addEventListener(ResultEvent.RESULT, onResult)
			service.send()
		}
		
		private function onResult(event:ResultEvent):void {
			helpData = event.result as XML
			applyHelpData()
		}
		
		private function applyHelpData():void {
			if (!helpData) {
				load()
				return
			}
			var tips:XMLList
			for (var clazz:String in map) {
				clazz = clazz.slice(clazz.lastIndexOf(":")+1)
				tips = helpData..tip.(@clazz == clazz)
				if (tips.length()) {
					for each(var tip:XML in tips)
						addHelpTips(tip)
				}
			}
		}
	}
}